package com.shujia.wyh.day27.network.tcpcoding;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/*
        使用多线程改进，多个客户端连接服务器
 */
public class ServerDemo3 {
    public static void main(String[] args) throws Exception {
        System.out.println("===============服务器启动================");
        //创建服务器端的Socket对象
        ServerSocket ss = new ServerSocket(12345);
        //循环接收客户端的连接
        while (true) {
            Socket socket = ss.accept();
            //将每个客户端的连接封装一个线程执行
            new ServerReaderThread(socket).start();
        }
    }
}

class ServerReaderThread extends Thread {
    private Socket socket;

    ServerReaderThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            while (true){
                //获取通道中的输入流对象，读取客户端发送的数据
                InputStream is = socket.getInputStream();
                byte[] bytes = new byte[1024];
                int length = is.read(bytes);
                String info = new String(bytes, 0, length);

                //获取客户端的ip和主机名
                InetAddress address = socket.getInetAddress();
                String ip = address.getHostAddress();
                String hostName = address.getHostName();
                System.out.println(ip + "，" + hostName + "发送的数据为：" + info);
            }


        } catch (IOException e) {
//            e.printStackTrace();
            System.out.println("客户端"+socket.getInetAddress().getHostName()+"下线了。。。。");
        }
    }
}
